const Config = require('../models/config').Config;

const CONFIG_KEYS = ['canUserUploadScripts'];

const globalConfig = {};

function loadConfig () {
  Config.find({}, function(error, configs) {
    configs.forEach(config => {
      if (CONFIG_KEYS.includes(config.key)) {
        globalConfig[config.key] = config.value;
      }
    })
  })
}

loadConfig();

exports.save = function (configs, done) {
  const ops = [];
  configs.forEach(config => {
    if (CONFIG_KEYS.includes(config.key)) {
      if (JSON.stringify(config.value) !== JSON.stringify(globalConfig[config.key])) {
        ops.push({
          updateOne: {
            filter: {key: config.key},
            update: {'$set': {value: config.value}},
            upsert: true
          }
        });
        globalConfig[config.key] = config.value;
      }
    }
  });
  if (ops.length > 0) {
    Config.bulkWrite(ops, done);
  }
};

exports.getConfigs = function () {
  const configs = [];
  CONFIG_KEYS.forEach(key => configs.push({key, value: globalConfig[key]}));
  return configs;
};
exports.globalConfig = globalConfig;
